<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑医嘱' : '新增医嘱' }}</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
        status-icon
      >
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="医嘱编号" prop="orderId">
              <el-input 
                v-model="form.orderId" 
                placeholder="系统自动生成" 
                disabled
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="医嘱类型" prop="type">
              <el-select 
                v-model="form.type" 
                placeholder="请选择医嘱类型"
                style="width: 100%"
              >
                <el-option label="长期医嘱" value="长期医嘱" />
                <el-option label="临时医嘱" value="临时医嘱" />
                <el-option label="检查医嘱" value="检查医嘱" />
                <el-option label="手术医嘱" value="手术医嘱" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="医嘱状态" prop="status">
              <el-select 
                v-model="form.status" 
                placeholder="请选择状态"
                style="width: 100%"
                :disabled="isEdit"
              >
                <el-option label="已开立" value="已开立" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">患者信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="患者" prop="patientId">
              <el-select 
                v-model="form.patientId" 
                filterable 
                remote 
                reserve-keyword
                placeholder="请输入患者姓名或ID搜索" 
                :remote-method="searchPatients"
                :loading="patientLoading"
                style="width: 100%"
                @change="handlePatientChange"
                :disabled="!!route.query.patientId || isEdit"
              >
                <el-option 
                  v-for="item in patientOptions" 
                  :key="item.id" 
                  :label="`${item.name} (${item.patientId})`"
                  :value="item.id" 
                >
                  <div class="patient-option">
                    <span>{{ item.name }}</span>
                    <span class="patient-id">{{ item.patientId }}</span>
                    <span class="patient-info">{{ item.gender }} {{ item.age }}岁</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="医疗记录" prop="medicalRecordId">
              <el-select 
                v-model="form.medicalRecordId" 
                filterable
                placeholder="请选择关联的医疗记录" 
                style="width: 100%"
                :disabled="!!route.query.medicalRecordId || isEdit"
              >
                <el-option 
                  v-for="item in medicalRecordOptions" 
                  :key="item.id" 
                  :label="`${item.visitId} (${formatDate(item.visitDate)})`"
                  :value="item.id" 
                >
                  <div class="record-option">
                    <span>就诊ID: {{ item.visitId }}</span>
                    <span class="record-info">{{ formatDate(item.visitDate) }}</span>
                    <el-tag size="small" type="info">{{ item.departmentName }}</el-tag>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="诊断" prop="diagnosis">
              <el-select 
                v-model="form.diagnosis" 
                placeholder="请选择诊断"
                style="width: 100%"
                :disabled="isEdit"
              >
                <el-option 
                  v-for="item in diagnosisOptions" 
                  :key="item.id" 
                  :label="item.name"
                  :value="item.name" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="开立科室" prop="departmentId">
              <el-select 
                v-model="form.departmentId" 
                placeholder="请选择科室" 
                filterable
                style="width: 100%"
                @change="handleDepartmentChange"
                :disabled="!!route.query.departmentId || isEdit"
              >
                <el-option 
                  v-for="item in departmentOptions" 
                  :key="item.id" 
                  :label="item.name" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="开立医生" prop="doctorId">
              <el-select 
                v-model="form.doctorId" 
                placeholder="请选择医生" 
                filterable
                style="width: 100%"
                :disabled="!!route.query.doctorId || isEdit"
              >
                <el-option 
                  v-for="item in doctorOptions" 
                  :key="item.id" 
                  :label="`${item.name} (${item.title})`" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">医嘱内容</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="医嘱内容" prop="content">
              <el-input 
                v-model="form.content" 
                type="textarea" 
                :rows="3" 
                placeholder="请输入医嘱的详细内容"
                :disabled="isEdit && form.status !== '已开立'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="执行频次" prop="frequency">
              <el-select 
                v-model="form.frequency" 
                placeholder="请选择执行频次"
                style="width: 100%"
                :disabled="isEdit && form.status !== '已开立'"
              >
                <el-option label="每日一次" value="每日一次" />
                <el-option label="每日两次" value="每日两次" />
                <el-option label="每日三次" value="每日三次" />
                <el-option label="每周一次" value="每周一次" />
                <el-option label="立即执行" value="立即执行" />
                <el-option label="必要时执行" value="必要时执行" />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                placeholder="请选择开始时间"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled="isEdit && form.status !== '已开立'"
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                placeholder="长期医嘱可不填"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled="isEdit && form.status !== '已开立'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="医嘱说明" prop="instructions">
              <el-input 
                v-model="form.instructions" 
                type="textarea" 
                :rows="3" 
                placeholder="请输入医嘱说明、注意事项等"
                :disabled="isEdit && form.status !== '已开立'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="submitForm"
            :disabled="isEdit && form.status !== '已开立'"
          >
            保存
          </el-button>
          <el-button @click="cancelForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { medicalOrderAPI, patientAPI, departmentAPI, doctorAPI, medicalRecordAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'

// 路由相关
const route = useRoute()
const router = useRouter()
const orderId = computed(() => route.params.id)
const isEdit = computed(() => !!orderId.value)

// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  orderId: '',
  type: '长期医嘱',
  status: '已开立',
  patientId: route.query.patientId || '',
  medicalRecordId: route.query.medicalRecordId || '',
  diagnosis: '',
  departmentId: route.query.departmentId || '',
  doctorId: route.query.doctorId || '',
  content: '',
  frequency: '每日一次',
  startTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
  endTime: '',
  instructions: ''
})

// 表单验证规则
const rules = {
  type: [{ required: true, message: '请选择医嘱类型', trigger: 'change' }],
  patientId: [{ required: true, message: '请选择患者', trigger: 'change' }],
  medicalRecordId: [{ required: true, message: '请选择医疗记录', trigger: 'change' }],
  departmentId: [{ required: true, message: '请选择科室', trigger: 'change' }],
  doctorId: [{ required: true, message: '请选择医生', trigger: 'change' }],
  content: [{ required: true, message: '请输入医嘱内容', trigger: 'blur' }],
  frequency: [{ required: true, message: '请选择执行频次', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }]
}

// 患者选项
const patientOptions = ref([])
const patientLoading = ref(false)

// 医疗记录选项
const medicalRecordOptions = ref([])

// 诊断选项
const diagnosisOptions = ref([])

// 科室选项
const departmentOptions = ref([])

// 医生选项
const doctorOptions = ref([])

// 获取医嘱详情
const getMedicalOrderDetail = async () => {
  try {
    const res = await medicalOrderAPI.getMedicalOrder(orderId.value)
    // 填充表单数据
    Object.keys(form).forEach(key => {
      if (key in res.data && res.data[key] !== null) {
        form[key] = res.data[key]
      }
    })
    
    // 获取相关患者信息
    if (res.data.patientInfo) {
      patientOptions.value = [res.data.patientInfo]
    }
    
    // 获取医疗记录选项
    if (res.data.patientId) {
      getPatientMedicalRecords(res.data.patientId)
    }
    
    // 获取诊断选项
    if (res.data.medicalRecordId) {
      getMedicalRecordDiagnosis(res.data.medicalRecordId)
    }
    
    // 预加载科室医生信息
    if (form.departmentId) {
      getDoctorsByDepartment(form.departmentId)
    }
    
  } catch (error) {
    console.error('获取医嘱详情失败', error)
    ElMessage.error('获取医嘱详情失败')
  }
}

// 搜索患者
const searchPatients = async (query) => {
  if (query.length < 2) return
  patientLoading.value = true
  try {
    const res = await patientAPI.getPatients({ 
      name: query,
      limit: 10
    })
    patientOptions.value = res.data.patients
  } catch (error) {
    console.error('搜索患者失败', error)
  } finally {
    patientLoading.value = false
  }
}

// 处理患者变化
const handlePatientChange = (patientId) => {
  // 清空相关字段
  form.medicalRecordId = ''
  form.diagnosis = ''
  
  // 获取患者的医疗记录
  getPatientMedicalRecords(patientId)
}

// 获取患者的医疗记录
const getPatientMedicalRecords = async (patientId) => {
  if (!patientId) return
  try {
    const res = await medicalRecordAPI.getMedicalRecords({
      patientId,
      status: ['已完成', '已签名'],
      limit: 20
    })
    medicalRecordOptions.value = res.data.records || []
  } catch (error) {
    console.error('获取患者医疗记录失败', error)
  }
}

// 监听医疗记录变化
watch(() => form.medicalRecordId, (newVal) => {
  if (newVal) {
    getMedicalRecordDiagnosis(newVal)
  } else {
    diagnosisOptions.value = []
    form.diagnosis = ''
  }
})

// 获取医疗记录的诊断
const getMedicalRecordDiagnosis = async (recordId) => {
  if (!recordId) return
  try {
    const res = await medicalRecordAPI.getMedicalRecord(recordId)
    if (res.data.diagnosis && res.data.diagnosis.length > 0) {
      diagnosisOptions.value = res.data.diagnosis
    }
  } catch (error) {
    console.error('获取医疗记录诊断失败', error)
  }
}

// 获取科室列表
const getDepartments = async () => {
  try {
    const res = await departmentAPI.getDepartments({ status: '启用' })
    departmentOptions.value = res.data.departments
  } catch (error) {
    console.error('获取科室列表失败', error)
  }
}

// 根据科室获取医生列表
const getDoctorsByDepartment = async (departmentId) => {
  if (!departmentId) return
  try {
    const res = await doctorAPI.getDoctors({ 
      departmentId,
      status: '在职'
    })
    doctorOptions.value = res.data.doctors
  } catch (error) {
    console.error('获取医生列表失败', error)
  }
}

// 处理科室变化
const handleDepartmentChange = (departmentId) => {
  form.doctorId = '' // 清空已选医生
  getDoctorsByDepartment(departmentId)
}

// 提交表单
const submitForm = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          // 编辑模式
          await medicalOrderAPI.updateMedicalOrder(orderId.value, form)
          ElMessage.success('医嘱更新成功')
        } else {
          // 新增模式
          await medicalOrderAPI.createMedicalOrder(form)
          ElMessage.success('医嘱创建成功')
        }
        // 返回列表页
        router.push('/medical-orders/list')
      } catch (error) {
        console.error('保存医嘱失败', error)
        ElMessage.error(error.message || '保存失败')
      }
    } else {
      ElMessage.warning('请完善表单信息')
      return false
    }
  })
}

// 取消表单
const cancelForm = () => {
  ElMessageBox.confirm('确认放弃当前编辑内容？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/medical-orders/list')
  }).catch(() => {})
}

// 页面加载时获取数据
onMounted(() => {
  // 获取基础数据
  getDepartments()
  
  // 如果有查询参数中的患者ID，获取患者信息
  if (form.patientId) {
    patientAPI.getPatient(form.patientId).then(res => {
      patientOptions.value = [res.data]
      // 获取患者的医疗记录
      getPatientMedicalRecords(form.patientId)
    }).catch(error => {
      console.error('获取患者信息失败', error)
    })
  }
  
  // 如果有查询参数中的医疗记录ID，获取诊断信息
  if (form.medicalRecordId) {
    getMedicalRecordDiagnosis(form.medicalRecordId)
  }
  
  // 如果有查询参数中的科室ID，获取医生列表
  if (form.departmentId) {
    getDoctorsByDepartment(form.departmentId)
  }
  
  // 编辑模式下获取详情
  if (isEdit.value) {
    getMedicalOrderDetail()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patient-option, .record-option {
  display: flex;
  align-items: center;
}

.patient-id, .record-info {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.patient-info {
  margin-left: auto;
  color: #909399;
  font-size: 12px;
}
</style> 